'''
Created on Jan 25, 2013

@author: dexen
'''


import random

import dexen

from const import GEN_SIZE

ALIVE = "Alive"
DEAD = "Dead"

class Individual(dexen.BaseIndividual):
    def __init__(self):
        dexen.BaseIndividual.__init__(self)
        self.genotype = []
        #create a random genotype
        for _ in range(GEN_SIZE):
            self.genotype.append(random.randint(0,1))
        self.phenotype = None
        self.similarity = None
        self.state = ALIVE

    def reproduce(self, ind):
        #crossover
        child1, child2 = self.crossover(ind)
        
        #mutation
        child1.mutate()
        child2.mutate()
        
        #return the kids
        return child1, child2
    
    def crossover(self, ind):
        #create the kids
        child1 = Individual()
        child2 = Individual()
        child1.genotype = []
        child2.genotype = []
        
        #crossover
        z = random.randint(1, GEN_SIZE-2)
        for i in range(z):
            child1.genotype.append(self.genotype[i])
            child2.genotype.append(ind.genotype[i])
        for i in range(z, GEN_SIZE):
            child1.genotype.append(ind.genotype[i])
            child2.genotype.append(self.genotype[i])
        
        #return the two new individuals
        return  child1, child2
    
    def mutate(self):
        for i in range(GEN_SIZE):
            if random.random() < 0.01:
                if self.genotype[i]:
                    self.genotype[i] = 0
                else:
                    self.genotype[i] = 1
    
    def kill(self):
        self.state = DEAD
    
    def is_alive(self):
        return self.state == ALIVE 
    
    def __repr__(self):
        out = "---------- BaseIndividual ----------\n"
        out += "Id: %s\n"%(self._get_id()) 
        if self.genotype:
            out += "Genotype: Exists\n"
        else:
            out += "Genotype: None\n"
        if self.phenotype:
            out += "Phenotype: Exists\n"
        else:
            out += "Phenotype: None\n"        
        out += "similarity: %s\n"%(self.similarity)
        out += "-------------------------------\n"
        return out


#===============================================================================
# Testing
#===============================================================================
def test():
    ind = Individual()
    #print ind
    t = range(10)
    random.shuffle(t)
    print t
    
    
if __name__ == "__main__":
    test()
    